from common import exception
from config import configuration


class BasicMethod:
    """
    文件类型对应的扩展名，目前钉钉支持的格式如下，除音频文件最大2Mb外，其余类型支持最大20Mb
    image：jpg、gif、png、bmp
    voice：amr、mp3、wav
    video：mp4
    file：doc、docx、xls、xlsx、ppt、pptx、zip、pdf、rar
    """
    file_types = {
        'image': ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'svg', 'webp'],
        'voice': ['mp3', 'wav', 'ogg', 'm4a', 'aac', 'flac', 'amr'],
        'video': ['mp4', 'avi', 'mov', 'mkv', 'flv', 'wmv', 'webm', 'mpg', 'mpeg'],
        'file': ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'rar', 'sql']
    }

    @classmethod
    def check_context(cls, context):
        """
        检查上下文内容，在启用配置填充的前提下用本地配置补全缺失的配置；调用者传递的配置优先，本地配置仅作为候补配置
        :param context: 上下文信息
        :return: 配置补全后的完整上下文
        """
        if not configuration.ENABLE_FILL and not context:
            raise exception.CheckedException("配置信息为空！")
        elif not configuration.ENABLE_FILL:
            return context
        if not context:
            context = {
                configuration.DING_APP_KEY_ATT: configuration.DING_APP_KEY,
                configuration.DING_APP_SECRET_ATT: configuration.DING_APP_SECRET,
                configuration.DING_OPEN_CONVERSATION_ID_ATT: configuration.DING_OPEN_CONVERSATION_ID,
                configuration.DING_ROBOT_CODE_ATT: configuration.DING_ROBOT_CODE,
                configuration.SMS_ENDPOINT_ATT: configuration.SMS_ENDPOINT,
                configuration.SMS_SIGN_NAME_ATT: configuration.SMS_SIGN_NAME,
                configuration.SMS_PHONE_NUMBERS_ATT: configuration.SMS_PHONE_NUMBERS
            }
        else:
            default_values = {
                configuration.DING_APP_KEY_ATT: configuration.DING_APP_KEY,
                configuration.DING_APP_SECRET_ATT: configuration.DING_APP_SECRET,
                configuration.DING_OPEN_CONVERSATION_ID_ATT: configuration.DING_OPEN_CONVERSATION_ID,
                configuration.DING_ROBOT_CODE_ATT: configuration.DING_ROBOT_CODE,
                configuration.SMS_ENDPOINT_ATT: configuration.SMS_ENDPOINT,
                configuration.SMS_SIGN_NAME_ATT: configuration.SMS_SIGN_NAME,
                configuration.SMS_PHONE_NUMBERS_ATT: configuration.SMS_PHONE_NUMBERS
            }
            for key, default_value in default_values.items():
                # 检查 key 是否存在或者值为空
                # 使用 get 方法处理 key 可能不存在的情况
                if not context.get(key):
                    context[key] = default_value
        return context

    @classmethod
    def determine_file_type(cls, file_name) -> str:
        """
        根据文件的后缀名判别文件的类型，如果未匹配到已知类型，则返回空
        :param file_name: 带后缀的完整文件名
        :return: 文件类型
        """
        # 获取文件扩展名，并转换为小写
        file_extension = file_name.split('.')[-1].lower()
        # 根据扩展名判断文件类型
        for file_type, extensions in cls.file_types.items():
            if file_extension in extensions:
                return file_type
        return ''
